package sp.util.shiro;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
	
	private Cache<String, AtomicInteger> passwordRetryCache;
	 
	public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
		//根据echcache中的cache级别的name
		passwordRetryCache = cacheManager.getCache("passwordRetryCache");
	}

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,
            AuthenticationInfo info) {
    	//用户名
        String username = (String) token.getPrincipal();
        //重复次数记录+1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        
        System.out.println("用户正确的情况下当前第" + retryCount.incrementAndGet() + "次登录失败");
        if (retryCount.incrementAndGet() > 5) {
            //超过5次锁定
            throw new ExcessiveAttemptsException("您的登录失败次数已达上限,请10分钟后再试!");
        }

        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
           //登录成功,清空重复次数记录
            passwordRetryCache.remove(username);
        }
        return matches;
    }
}
